package com.yuyou.tas.lesson.service.impl;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.yuyou.tas.lesson.mapper.BaseChapterMapper;
import com.yuyou.tas.lesson.mapper.LessonClassChapterMapper;
import com.yuyou.tas.lesson.mapper.LessonResourceMapper;
import com.yuyou.tas.lesson.mapper.UpGradeDataMapper;
import com.yuyou.tas.lesson.service.ILessonChapterService;
import com.yuyou.tas.lesson.service.ILessonClassStudentService;
import com.yuyou.tas.lesson.service.ILessonService;
import com.yuyou.tas.lesson.service.IStudentService;
import com.yuyou.tas.lesson.service.IUpGradeDataService;
import com.yuyou.tas.service.api.lesson.dto.MergeStuDTO;
import com.yuyou.tas.service.api.lesson.entity.Lesson;
import com.yuyou.tas.service.api.lesson.entity.LessonChapter;
import com.yuyou.tas.service.api.lesson.entity.LessonClassStudent;
import com.yuyou.tas.service.api.lesson.entity.LessonResource;
import com.yuyou.tas.service.api.lesson.entity.Student;
import com.yuyou.tas.util.bean.ResBoolSimpleInfo;
import com.yuyou.tas.util.config.SystemConfig;
import com.yuyou.tas.util.enums.CommEnums;
import com.yuyou.tas.util.enums.lesson.LessonEnums;
import com.yuyou.tas.util.tool.DefindBeanUtils;
import com.yuyou.tas.util.tool.LogUtil;

@Service
public class UpGradeDataServiceImpl implements IUpGradeDataService{

	@Autowired
	private ILessonService lessonService;
	
	@Autowired
	private ILessonChapterService lessonChapterService;
	@Autowired
	private LessonResourceMapper lessonResourceMapper;
	@Autowired
	private BaseChapterMapper baseChapterMapper;
	
	@Autowired
	private LessonClassChapterMapper lessonClassChapterMapper;
	
	@Autowired
	private UpGradeDataMapper upGradeDataMapper;
	
	@Override
	@Transactional(rollbackFor=Exception.class,timeout=60)
	public ResBoolSimpleInfo<String> upgradeLesson(Long organId,Long userId) {
		
		Long sysOrganId=SystemConfig.SYS_ORGAN_ID;
		
		//找出已发布的，未同步的OID不为空的课程
		List<Lesson> lessonList=lessonService.findPubLessonByOrganId(organId);
		for(Lesson l:lessonList){
			
			Lesson pLesson=new Lesson();
			pLesson.setId(l.getId());
			pLesson.setIsSycn(1);
			lessonService.updateByPrimaryKeySelective(pLesson);
			
			Lesson newLesson=new Lesson();
			DefindBeanUtils.copyProperties(l, newLesson);
			
			//标准不需要学期年份
			newLesson.setBaseTrimesterId(null);
			newLesson.setDataYear(null);
			
			newLesson.setAuthOrganizationId(sysOrganId);
			newLesson.setpId(null);
			newLesson.setoId(null);
			newLesson.setStatus(LessonEnums.status.init.getValue());
			newLesson.setIsStan(1);
			newLesson.setType(LessonEnums.type.standard.getValue());
			newLesson.setId(null);
			newLesson.setCreateUser(null);
			lessonService.insert(newLesson);
			
			List<LessonChapter> lcList=lessonChapterService.findLessonChapterByLessId(l.getId());
			for(LessonChapter lc:lcList){
				LessonChapter newLessonChapter=new LessonChapter();
				DefindBeanUtils.copyProperties(lc, newLessonChapter);
				newLessonChapter.setLessonId(newLesson.getId());
				newLessonChapter.setAuthOrganizationId(sysOrganId);
				newLessonChapter.setpId(null);
				newLessonChapter.setStatus(LessonEnums.status.init.getValue());
				newLessonChapter.setIsStan(1);
				newLessonChapter.setId(null);
				newLessonChapter.setCreateUser(null);
				lessonChapterService.insert(newLessonChapter);
			}
		}
		
		
		
		return ResBoolSimpleInfo.getSuccessInfo();
	}

	@Override
	public ResBoolSimpleInfo<String> sycnResoreceType() {

		//更新 lesson_class_id is null
		List<LessonResource> lrNull=lessonResourceMapper.findByLcNull();
		for(LessonResource lr :lrNull){
			int c=baseChapterMapper.findCountByCourseUrl(lr.getResourceId());
			if(c>0){
				LessonResource u=new LessonResource();
				u.setId(lr.getId());
				u.setType(CommEnums.resourceType.COURSE.getValue());
				lessonResourceMapper.updateByPrimaryKeySelective(u);
				continue;
			}
			int d=baseChapterMapper.findCountByLectureUrl(lr.getResourceId());
			if(d>0){
				LessonResource u=new LessonResource();
				u.setId(lr.getId());
				u.setType(CommEnums.resourceType.LECTURE.getValue());
				lessonResourceMapper.updateByPrimaryKeySelective(u);
				continue;
			}
		}
		
		
		
		
		//更新 lesson_class_id is not null
		List<LessonResource> lrNotNull=lessonResourceMapper.findByLcNotNull();
		for(LessonResource lr :lrNotNull){
			int c=lessonClassChapterMapper.findCountByCourseUrl(lr.getResourceId());
			if(c>0){
				LessonResource u=new LessonResource();
				u.setId(lr.getId());
				u.setType(CommEnums.resourceType.COURSE.getValue());
				lessonResourceMapper.updateByPrimaryKeySelective(u);
				continue;
			}
			int d=lessonClassChapterMapper.findCountByLectureUrl(lr.getResourceId());
			if(d>0){
				LessonResource u=new LessonResource();
				u.setId(lr.getId());
				u.setType(CommEnums.resourceType.LECTURE.getValue());
				lessonResourceMapper.updateByPrimaryKeySelective(u);
				continue;
			}
		}		
		
		
		return ResBoolSimpleInfo.getSuccessInfo();
	}

	@Autowired
	private IStudentService studentService;
	
	@Autowired
	private ILessonClassStudentService lessonClassStudentService;
	
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	/**
	 * 情况1.o_id查出多条相同，机构不一样
	 * 情况2.o_id有，new_id没有，new_id有，o_id没有
	 * @throws Exception 
	 */
	@Override
	@Transactional
	public ResBoolSimpleInfo<String> mergeStudent(List<MergeStuDTO> list) throws Exception {
		int logIndex=0;
		for(MergeStuDTO studentExcel:list){
			logIndex++;
			LogUtil.info(logger, logIndex+"-"+logIndex+"-"+logIndex+"-"+logIndex+"-"+logIndex+"-"+logIndex+"-"+logIndex+"-");
			LogUtil.info(logger, studentExcel.getOldStudentName()+"-"+studentExcel.getOldStudentName()+"-"+studentExcel.getOldStudentName()+"-"+studentExcel.getNewStudentName()+"-"+studentExcel.getNewStudentName()+"-"+studentExcel.getNewStudentName()+"-"+studentExcel.getNewStudentName()+"-");
			List<Student> oldStuList=studentService.findByOId(Long.valueOf(studentExcel.getOldStudentId()));
			List<Student> newStuList=studentService.findByOId(Long.valueOf(studentExcel.getNewStudentId()));
			LogUtil.info(logger, logIndex+":"+studentExcel.getOldStudentName()+":"+"-"+"oldStuList:"+oldStuList.size()+"-"+"newStuList:"+newStuList.size());
			//1:都没有直接返回
			if(oldStuList.size()==0 && newStuList.size()==0){
				LogUtil.info(logger, logIndex+":"+studentExcel.getOldStudentName()+":"+studentExcel.getOldStudentName()+":"+"direct return");
				continue;
			}
			//2:删除的学生找不到，直接更新预留手机号码
			else if(oldStuList.size()==0 && newStuList.size()>0){
					//直接更新保留学生的（预留手机号码）
					String oldPhone=studentExcel.getOldStudentPhone();
					for(Student newS:newStuList){
						Student newUpdateStu=new Student();
						newUpdateStu.setId(newS.getId());
						newUpdateStu.setSlavePhoneNo(oldPhone);
						studentService.updateByPrimaryKeySelective(newUpdateStu);
					}
					LogUtil.info(logger, logIndex+":"+studentExcel.getOldStudentName()+":"+"update slave phone");
					continue;
				}
			//3:都存在，区分不同机构情况
			else if(oldStuList.size()>0){				
				for(Student oldS:oldStuList){
					
					//判断要保留的学生是否存在
					Student newStudent=studentService.selectByOrgan7OId(Long.valueOf(studentExcel.getNewStudentId()), oldS.getAuthOrganizationId());
					
					if(newStudent==null){					
						//a.插入一条有保留的学生
						newStudent=new Student();
						newStudent.setAuthOrganizationId(oldS.getAuthOrganizationId());
						//年级
						if(!StringUtils.isEmpty(studentExcel.getNewStudentGrade())){							
							newStudent.setBaseSectionId(Long.valueOf(studentExcel.getNewStudentGrade()));
						}
						newStudent.setName(studentExcel.getNewStudentName());
						newStudent.setoId(Long.parseLong(studentExcel.getNewStudentId()));
						newStudent.setPhoneNo(studentExcel.getNewStudentPhone());
						newStudent.setSex(Integer.parseInt(studentExcel.getNewStudentSex()));
						//备用手机号码
						newStudent.setSlavePhoneNo(oldS.getPhoneNo());
						newStudent.setStudentNo(studentExcel.getNewStudentNo());	
						
						Student s=studentService.selectByOrganIdPhoneName(newStudent.getAuthOrganizationId() , newStudent.getPhoneNo() , newStudent.getName());
						if(s != null){
							throw new Exception("已存在同个姓名和手机号学生，请检查是否有误");
						}
						
						studentService.insert(newStudent);
					}
										
					//b.更改lesson_class_student
					List<LessonClassStudent> oldLcsList=lessonClassStudentService.findByStudentOId(oldS.getoId());
					for(LessonClassStudent oldLcs:oldLcsList){
						//查询要替换成保留的学生有没有班级关系(1->A,2-A),(1->A,2-B)
						LessonClassStudent uniStudentNew=lessonClassStudentService.selectByOrgan7OId(
								oldLcs.getLessonClassOId(),
								//替换的学生id
								newStudent.getoId(),
								oldLcs.getAuthOrganizationId()
								);
						

						if(uniStudentNew!=null){
							LessonClassStudent lcsUp=new LessonClassStudent();
							lcsUp.setId(oldLcs.getId());
							lcsUp.setRegStatus(0);
							//如果已经存在,更新状态为在读
							lessonClassStudentService.updateByPrimaryKeySelective(lcsUp);
						}
						else{
							//没有，插入一条在读信息
							LessonClassStudent lcsUp=new LessonClassStudent();
							lcsUp.setAuthOrganizationId(oldLcs.getAuthOrganizationId());
							lcsUp.setLessonClassId(oldLcs.getLessonClassId());
							lcsUp.setLessonClassOId(oldLcs.getLessonClassOId());
							lcsUp.setRegStatus(0);
							//替换的学生id
							lcsUp.setStudentId(newStudent.getId());
							lcsUp.setStudentOId(newStudent.getoId());	
							lessonClassStudentService.insert(lcsUp);
						}
						

						
						//删除旧的要处理的就学生班级关系
						lessonClassStudentService.deleteByPrimaryKey(oldLcs.getId());
						
					}
					
					//c.反馈
					
					//1.反馈(内容)一份
					Long newStudentId=newStudent.getId();
					List<Map<String,Object>> fdMapList=upGradeDataMapper.findByFdUserId(oldS.getAuthOrganizationId(), oldS.getId());
					if(fdMapList!=null&&fdMapList.size()>0){	
						
						for(Map<String,Object> m:fdMapList){
							Map<String,Object> newFdMap=upGradeDataMapper.select1Fd((Long)m.get("feedback_class_id"), newStudentId);
							System.out.println(1);
							if(newFdMap==null){
								upGradeDataMapper.upFdUserIdById((Long)m.get("id"),newStudentId);
								//2.反馈(评论)
								upGradeDataMapper.upFdCByFdId((Long)m.get("id"),newStudentId);
							}else{								
								upGradeDataMapper.delFdById((Long)m.get("id"));
								upGradeDataMapper.delFdCByFdId((Long)m.get("id"));
							}
						}
						

					}

					
					//2.反馈（优秀学生）一份
					List<Map<String,Object>> fdSEMapList=upGradeDataMapper.findFdSE(oldS.getAuthOrganizationId(), oldS.getId());
					if(fdSEMapList!=null&&fdSEMapList.size()>0){
						
						for(Map<String,Object> m:fdSEMapList){
							Map<String,Object> newFdSEMap=upGradeDataMapper.select1FdSE((Long)m.get("feedback_class_id"), newStudentId);
							if(newFdSEMap==null){
								upGradeDataMapper.upFdSEStuIdById((Long)m.get("id"), newStudentId);
							}else{
								upGradeDataMapper.delFdSEById((Long)m.get("id"));
							}
						}

					}

					//3.反馈（送花老师）一份
					List<Map<String,Object>> fdTPMapList=upGradeDataMapper.findFdTP(oldS.getAuthOrganizationId(), oldS.getId());
					if(fdTPMapList!=null&&fdTPMapList.size()>0){
						
						for(Map<String,Object> m:fdTPMapList){
							Map<String,Object> newFdTPMap=upGradeDataMapper.select1FdTP((Long)m.get("feedback_class_id"), newStudentId,(Integer)m.get("is_praise"));
							if(newFdTPMap==null){
								upGradeDataMapper.upFdTPSUserIdById((Long)m.get("id"), newStudentId);
							}else{
								upGradeDataMapper.delFdTPById((Long)m.get("id"));
							}
							
						}
					}						


					
					//d.学业诊断
					//1.诊断（报告）一份，诊断（知识点）一份
					List<Map<String,Object>> reportMapList=upGradeDataMapper.findReport(oldS.getAuthOrganizationId(), oldS.getId());
					if(reportMapList!=null&&reportMapList.size()>0){
						for(Map<String,Object> m:reportMapList){
							Map<String,Object> newReportMap=upGradeDataMapper.select1Report(
									(Long)m.get("lesson_class_id"), 
									newStudentId,
									(Long)m.get("exam_model_id"));
							if(newReportMap==null){
								upGradeDataMapper.upReportStuIdById((Long)m.get("id"), newStudentId);
								//更新诊断（知识点）
								upGradeDataMapper.upReportKnByReport(newStudentId,(Long)m.get("id"));
							}else{
								upGradeDataMapper.delReportById((Long)m.get("id"));
								//删除诊断（知识点）
								upGradeDataMapper.delReportKnByReportId((Long)m.get("id"));
							}
						}

					}	

					//1.诊断（题目）一份
					List<Map<String,Object>> reportQuMapList=upGradeDataMapper.findReportQu(oldS.getAuthOrganizationId(), oldS.getId());
					if(reportQuMapList!=null&&reportQuMapList.size()>0){
						for(Map<String,Object> m:reportQuMapList){
							Map<String,Object> newReportQuMap=upGradeDataMapper.select1ReportQu(
									(Long)m.get("lesson_class_id"), 
									newStudentId,
									(Long)m.get("exam_model_ques_id"));
							if(newReportQuMap==null){
								upGradeDataMapper.upReportQuStuIdById((Long)m.get("id"), newStudentId);
							}else{
								upGradeDataMapper.delReportQuById((Long)m.get("id"));
							}
						}

					}
					
					//e.更新SlavePhoneNo()
					Student newUpdateStu=new Student();
					newUpdateStu.setId(newStudent.getId());
					newUpdateStu.setSlavePhoneNo(oldS.getPhoneNo());
					studentService.updateByPrimaryKeySelective(newUpdateStu);
					
					//f.删除该学生
					studentService.deleteByPrimaryKey(oldS.getId());
					
				}	
				LogUtil.info(logger, logIndex+":"+studentExcel.getOldStudentName()+":"+"all");
			}				
		}
		
		return ResBoolSimpleInfo.getSuccessInfo();
	}
 
	
	
	
    
}